package servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import services.EmailServiceImpl;

import models.EmailDTO;

/**
 * @author 	Sami Diab
 * @since 	16/11/2011
 * Servlet implementation class AddEmail
 */
//@WebServlet("/ManageEmail")
@WebServlet(name="ManageEmail", urlPatterns={"/JSP/Sami/Admin/ManageEmail"})
public class ManageEmail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @author 	SAMI DIAB
	 * @since	16/11/2011
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//Parameters to retrieve
		
		//The action type parameter
		String actionType = (String) request.getParameter("actionType");
		
		//The email address to be added
		String emailAddress;
		
		//The email addresses to be removed
    	String[] emailAdresses;
    	
    	if(actionType != null){
    		
			if(actionType.equals("AddEmail")) 
			{
			    emailAddress = (String) request.getParameter("emailAddress");
				AddEmail(emailAddress);
				
			}
			else if(actionType.equals("DeleteEmail"))
			{
		    	emailAdresses = request.getParameterValues("emailAddresses");
		    	
				if(emailAdresses != null && emailAdresses.length > 0){
					
					for(int i = 0; i < emailAdresses.length; i++)
					{
						DeleteEmail(emailAdresses[i]);
					}
				}
			}
    	}
	    //important forward it back to the login page again. 
    	request.getRequestDispatcher("Newsletter.jsp").forward(request, response);
		
	}
	
	private void DeleteEmail(String emailAddress)
	{
		EmailServiceImpl esi = new EmailServiceImpl();
		boolean exists = esi.EmailExists(emailAddress);
		
		if(exists == false)
		{
			esi.Remove(emailAddress);//Add(new EmailDTO(emailAddress));
		}
	}
	
	private void AddEmail(String emailAddress)
	{
		EmailServiceImpl esi = new EmailServiceImpl();
		boolean exists = esi.EmailExists(emailAddress);
		
		if(exists == false)
		{
			esi.Add(new EmailDTO(emailAddress));
		}
	}

}
